class ResourcesController < ApplicationController
  #权限验证
  before_filter :auth  
  layout "admin"
  def index
    #    redirect_to :action=>'list'
    redirect_to params.merge!(:action => 'list')
  end

  def list
    @section = Section.new
    @col = Section.new
    @res_name = params[:res_name]
    @channel_id = params[:channel_id]
    @col_id = params[:col_id]
    @page = params[:page]
    #提交表单为post
    if request.post?
      @resource_search = params[:resource]
      name = @resource_search[:name]                  
      channel_id = params[:section][:channel_id]
      col_id = params[:col][:id]
      @section = Section.new(params[:section])      
      if !channel_id.empty?
        if !col_id.nil? && !col_id.empty?
          s_name = name
          @channel_id = channel_id
          @col_id = col_id
          @resources = Resource.paginate :per_page => $perPage, :page =>  params[:page],
            :include => [:section],
            :conditions => ['name like ? and col_id = ?   ',
            "%#{name}%",Section.find(col_id)],
            :order => 'col_id,orders asc'
        else
          s_name = name
          @channel_id = channel_id          
          @resources = Resource.paginate :per_page => $perPage, :page =>  params[:page],
            :include => [:section],
            :conditions => ['name like ? and col_id in (?)   ',
            "%#{name}%",Section.find_all_by_channel_id(channel_id)],
            :order => 'col_id,orders asc'
        end        
      else
        if !col_id.nil? && !col_id.empty?
          s_name = name
          @channel_id = nil
          @col_id = col_id
          @resources = Resource.paginate :per_page => $perPage, :page =>  params[:page],
            :conditions => ['name like ? and col_id = ? ', "%#{name}%",Section.find(col_id)],
            :order => 'col_id,orders asc'
        else
          s_name = name
          @channel_id = nil
          @col_id = col_id
          @resources = Resource.paginate :per_page => $perPage, :page =>  params[:page],
            :conditions => ['name like ? ', "%#{name}%"],
            :order => 'col_id,orders asc'
        end
        
      end
    else      
      if @res_name.nil?
        unless @channel_id.nil?
          if !col_id.nil? && !col_id.empty?
            @col_id = col_id
            @resources = Resource.paginate :per_page => $perPage, :page =>  params[:page],
              :include => [:section],
              :conditions => ['col_id = ?  ',
              Section.find(col_id)],
              :order => 'col_id,orders asc'
          else
            @resources = Resource.paginate :per_page => $perPage, :page =>  params[:page],
              :include => [:section],
              :conditions => ['col_id in (?)  ',
              Section.find_all_by_channel_id(@channel_id)],
              :order => 'col_id,orders asc'
          end
          
        else
          if !col_id.nil? && !col_id.empty?
            @col_id = col_id
            @resources = Resource.paginate  :page => params[:page],
              :per_page => $perPage,
              :conditions => ['col_id = ?  ',
              Section.find(col_id)],
              :order => "col_id,orders asc"
          else
            @resources = Resource.paginate  :page => params[:page],
              :per_page => $perPage,
              :order => "col_id,orders asc"
          end
        end
      else
        s_name = @res_name
        unless @channel_id.nil?
          if !@col_id.nil? && !@col_id.empty?
            @resources = Resource.paginate :per_page => $perPage, :page =>  params[:page],
              :conditions => ['name like ? and col_id = ? ', "%#{s_name}%",Section.find(@col_id)],
              :order => 'col_id,orders asc'
          else
            @resources = Resource.paginate :per_page => $perPage, :page =>  params[:page],
              :conditions => ['name like ? and col_id in (?) ', "%#{s_name}%",Section.find_all_by_channel_id(@channel_id)],
              :order => 'col_id,orders asc'
          end          
        else
          if !@col_id.nil? && !@col_id.empty?
            @resources = Resource.paginate :per_page => $perPage, :page =>  params[:page],
              :conditions => ['name like ? and col_id = ? ', "%#{s_name}%",Section.find(@col_id)],
              :order => 'col_id,orders asc'
          else
            @resources = Resource.paginate :per_page => $perPage, :page =>  params[:page],
              :conditions => ['name like ? ', "%#{s_name}%"],
              :order => 'col_id,orders asc'
          end          
        end        
      end
    end

    if request.post?
      ch_id = params[:section][:channel_id]
      #精选劲图推荐频道
      if ch_id.to_i != 0     
        @resources = Resource.paginate :per_page => $perPage, :page =>  params[:page],
          :conditions => ['name like ? and channel_id = ? ', "%#{@res_name}%",ch_id],
          :order => 'click_num desc'
      end
    else
      ch_id = params[:channel_id]
      if ch_id.to_i != 0
        @resources = Resource.paginate :per_page => $perPage, :page =>  params[:page],
          :conditions => ['name like ? and channel_id = ? ', "%#{@res_name}%",ch_id],
          :order => 'click_num desc'
      end
    end

    #查询项参数
    @resource = Resource.new
    @resource.name = s_name
    @res_name = s_name
    @sections = Section.find_all_by_level @section[:level]
    @section = Section.new
    @section.channel_id = @channel_id
    @col = Section.new
    @col.id = @col_id
    @page = params[:page]    
    #功能名
    @titles = "资源列表"
  end


  def show
    @resource = Resource.find(params[:id])
    @titles = "资源详细信息---"+@resource.name
  end


  def new
    @resource = Resource.new
    #功能名
    @titles = "新增资源"
  end


  def edit
    @resource = Resource.find(params[:id])
    sec = Section.find(@resource.col_id)
    @section = Section.find(:all, :conditions => ["channel_id = ?", sec.channel_id]).collect { |section| [section.name, section.id] }
    @tags = ""
    rs = ResTag.find_all_by_res_id @resource.id
    rs.each do |r|
      @tags = @tags + Tag.find(r.tag_id).name + ","
    end
    @page = params[:page]
    @titles = "编辑资源---"+@resource.name
  end


  def create
    @resource = Resource.new(params[:resource])   
    if @resource[:orders].nil?
      re = Resource.find_last_by_col_id @resource.col_id
      @resource.orders = re.orders + 1
    end
    #根据资源名称设置标签
    tags = Tag.find :all
    lel = $res_default
    tags.each do |t|
      unless @resource.name.index(t.name).nil?
        if t.level.to_i <= lel.to_i
          lel = t.level
        end
      end
    end

    begin
      #上传并解压文件
      rel_path = DataFile.saveZip(params[:upload])
      dirs=File.join($upload_path,rel_path)
      #得到的图片的数组
      src_arry = Array.new
      DataFile.traverse_dir File.join(dirs, $ssrc),src_arry
      if @resource.is_dy        
        src_arry.each do |src|          
          img = MiniMagick::Image.from_file src
          file_name = File.basename(src)
          dest_small = File.join(dirs,$small,file_name)
          img.write dest_small
          dest_large = File.join(dirs,$larger,file_name)
          img.write dest_large
          dest_large = File.join(dirs,$src,file_name)
          img.write dest_large
        end
      else
        src_arry.each do |src|
          handle_img src,dirs
        end
      end
      
      @resource.res_dir = rel_path
    rescue
      @resource = Resource.new
      #功能名
      @titles = "新增资源--目录名重复"
      render :action => "new"
    end


    resource = Resource.find_all_by_orders @resource[:orders]
    @resource.level = lel
    if !@resource.section.nil? && @resource && @resource.save && !resource.nil? && @resource.errors.empty?
      #根据资源名称设置标签
      tags.each do |t|
        unless @resource.name.index(t.name).nil?
          rs = ResTag.create(:resource => @resource,:tag => t)
          @resource.res_tag <<  rs
          t.res_tag <<  rs
          rs.save
        end
      end
      flash[:notice] = "新建资源成功"
      redirect_to :action=>'new'
    else
      flash[:notice] = "选个频道栏目吧"
      @titles = "新增资源-----错误，选个频道栏目吧"     
    end
  end


  def update
    @resource = params[:resource]
    @page = params[:pages][:page]    
    if @resource[:col_id].nil?
      render :action => "index"
    end
    tags = ResTag.find_all_by_res_id @resource[:id]
    tags.each do |tg|
      ResTag.delete(tg.id)
    end
    res = Resource.find @resource[:id]
    tag_array = params[:tags].split(",");
    lel = $res_default
    tag_array.each do |tg|
      tag1 = Tag.find_last_by_name tg
      unless tag1.nil?
        if tag1.level.to_i <= lel.to_i
          lel = tag1.level
        end
        rs = ResTag.create(:resource => res,:tag => tag1)
        res.res_tag <<  rs
        tag1.res_tag <<  rs
        rs.save
      else
        ta = Tag.new(:name => tg,:level => lel.to_s)
        ta.save
        rs = ResTag.create(:resource => res,:tag => ta)
        res.res_tag <<  rs
        ta.res_tag <<  rs
        rs.save
      end
    end

    @resource[:level] = lel
    params[:page] = @page
    if Resource.update(@resource[:id], @resource)
      flash[:notice] = '更新成功'
      redirect_to params.merge!(:action => 'index')
    else
      render :action => "edit"
    end
  end

  # 根据频道查询栏目(编辑)
  def select_col_with_ajax
    @section = Section.find(:all, :conditions => ["channel_id = ?", params[:channel_id]]).collect { |section| [section.name, section.id] }
    render :partial => 'choose_col'
  end


  # 根据频道查询栏目(增加)
  def select_with_ajax
    @section = Section.find(:all, :conditions => ["channel_id = ?", params[:channel_id]]).collect { |section| [section.name, section.id] }
    render(:layout => false)
  end

  # 生成小图，大图
  def handle_img src,dirs
    if File.exists?(src)
      file_name = File.basename(src)
      dest = File.join(dirs,$small,file_name)
      DataFile.compress_pic(dest, src, $small_size)
      dest = File.join(dirs,$larger,file_name)
      DataFile.compress_pic(dest, src, $larger_size)
      dest = File.join(dirs,$src,file_name)
      src_size = File.size src
      if src_size > 300000
        dsize = 400
      elsif src_size < 300000 && 200000 < src_size
        dsize = 500
      else
        dsize = 600
      end
      DataFile.compress_pic(dest, src, dsize)
    end
  end

  def delete
    resource = Resource.find(params[:id])
    ResTag.delete_all("res_id = #{resource.id}")
    resource.destroy
    redirect_to :action=>'index'
  end

  def scan_upload
    dy = params[:is_dy]
    col_arry  = []
    col_arry = scan_dir($img_upload,col_arry)
    #循环删除的res array
    res_obj_array = []
    #取得栏目的txt
    col_arry.each do |col_path|
      col_name = IO.read(col_path)
      #创建默认频道下的栏目
      section = Section.find_last_by_name(col_name)
      if section.nil?
        section = Section.new
        section.name = col_name
        section.x = 1
        section.y = 1
        section.status = false
        section.channel_id = $temp_channel
        section.col_type = 1
        section.is_ad = false
        section.level = $col_level
        section.save
      end
      col_dir = File.dirname(col_path)
      #资源的数组
      res_array = []
      res_array = scan_img(col_dir,res_array)

      res_array.each_with_index do|res_path,index|
        #拷贝文件夹下文件到目标文件夹
        timeStr = Time.now.strftime('%Y/%m/%d')
        #拷贝的相对路径
        dir_path = File.join(timeStr,Time.now.to_i.to_s)
        #拷贝的目标目录
        real_path = File.join($upload_path,dir_path)

        res_name = IO.read(res_path)
        resource = Resource.find_last_by_name(res_name)
        if resource.nil?
          resource = Resource.new
          resource.name = res_name
          #根据资源名称取得级别
          tags = Tag.find :all
          lel = $res_default
          tags.each do |t|
            unless resource.name.index(t.name).nil?
              if t.level.to_i <= lel.to_i
                lel = t.level
              end
            end
          end


          resource.level = lel
          resource.orders = index.to_i + 1
          resource.status = true
          resource.col_id = section.id
          resource.res_type = 1
          resource.res_dir = dir_path
          resource.save

          #根据资源名称设置标签
          tags.each do |t|
            unless resource.name.index(t.name).nil?
              rs = ResTag.create(:resource => resource,:tag => t)
              resource.res_tag <<  rs
              t.res_tag <<  rs
              rs.save
            end
          end          
          res_dir = File.dirname(res_path)
          img_array = []
          img_array = traverse_dir(res_dir,img_array)
          img_array.each do | img |
            base_name = File.basename(img)
            to_path = File.join(real_path,$ssrc)
            dest_dir = File.join(to_path,base_name)
            require "fileutils.rb"
            FileUtils.makedirs(to_path)
            FileUtils.cp img, dest_dir
            #创建存放大小图片的文件夹
            FileUtils.makedirs File.join(real_path, $small)
            FileUtils.makedirs File.join(real_path, $larger)
            FileUtils.makedirs File.join(real_path, $src)
            if dy == '1'
              img = MiniMagick::Image.from_file dest_dir
              file_name = File.basename(dest_dir)
              dest_small = File.join(real_path,$small,file_name)
              img.write dest_small
              dest_large = File.join(real_path,$larger,file_name)
              img.write dest_large
              dest_large = File.join(real_path,$src,file_name)
              img.write dest_large
            else
              handle_img dest_dir,real_path
            end
            
          end
        end
        res_obj_array << resource
      end
    end
    #进去的资源进行去重
    #需要删除的res array
    res_obj_array.each_with_index { |res_obj, index|
      res_list = Resource.find_all_by_name res_obj.name
      res_list.each do |res_o|
        if res_o.id != res_obj.id && res_o.col_id == res_obj.col_id
          res_o.destroy
        end
      end
    }

    redirect_to :action=>'index'
  end

  #扫描静态资源栏目
  def scan_dir(file_path,col_arry)
    if File.directory? file_path
      Dir.foreach(file_path) do |file|
        if file!="." and file!=".."
          scan_dir(file_path+"/"+file,col_arry)
        end
      end
    elsif file_path[/\.txt$/] and !file_path.include?("/src/")
      col_name = IO.read(file_path).to_s
      unless col_name == ""
        col_arry << file_path
      end
    else
    end
    return col_arry
  end

  #扫描专辑
  def scan_img(file_path,res_arry)
    if File.directory? file_path
      Dir.foreach(file_path) do |file|
        if file!="." and file!=".."
          scan_img(file_path+"/"+file,res_arry)
        end
      end
    elsif file_path[/\.txt$/] and file_path.include?("/src/")
      res_name = IO.read(file_path).to_s
      unless res_name == ""
        res_arry << file_path
      end
    else
    end
    return res_arry
  end

  #扫描图片
  def traverse_dir(file_path,img_array)
    if File.directory? file_path
      Dir.foreach(file_path) do |file|
        if file!="." and file!=".."
          traverse_dir(file_path+"/"+file,img_array)
        end
      end
    elsif file_path[/\.gif$/] || file_path[/\.jpg$/]
      img_array << file_path
    else
    end
    return img_array
  end

  def destroy_selected
    if not params[:resource_id].nil?
      begin
        Resource.transaction do          
          params[:resource_id].each do |res_id|
            unless res_id.empty?
              @resource = Resource.find(res_id)
              @resource.destroy
            end
          end
        end
        flash[:notice] = "删除数据成功！"
      rescue
        flash[:notice] = "删除数据失败！"
      end
    else
      flash[:notice] = '请选择要删除的资源！'
    end
    redirect_to :action=>'list'
  end

  def move_selected    
    if not params[:resource_id].nil?
      unless params[:section_tag] == 0
        begin
          Resource.transaction do
            params[:resource_id].each do |res_id|
              unless res_id.empty?
                resource = Resource.find(res_id)
                res_list = Resource.find(:all,
                  :conditions => ["name = ? and col_id = ? ", resource.name, params[:section_tag]])
                if res_list.size == 0
                  resource.update_attribute('col_id', params[:section_tag])
                end
              end
            end
          end
          flash[:notice] = "移动资源成功！"
        rescue
          flash[:notice] = "移动资源失败！"
        end
      else
        flash[:notice] = '请选择要移动的资源！'
      end
    end
    redirect_to :action=>'list'
  end

  def copy_selected    
    if not params[:resource_id].nil?
      unless params[:section_tag] == 0
        begin
          Resource.transaction do
            params[:resource_id].each do |res_id|
              unless res_id.empty?
                resource = Resource.find(res_id)
                res_list = Resource.find(:all,
                  :conditions => ["name = ? and col_id = ? ", resource.name, params[:section_tag]])
                if res_list.size == 0
                  res = Resource.new
                  res.name = resource.name
                  res.col_id = params[:section_tag]
                  res.level = resource.level
                  res.orders = resource.orders
                  res.status = resource.status
                  res.desc = resource.desc
                  res.res_type = resource.res_type
                  res.res_dir = resource.res_dir
                  res.save
                end
              end
            end
          end
          flash[:notice] = "复制资源成功！"
        rescue
          flash[:notice] = "复制资源失败！"
        end
      else
        flash[:notice] = '请选择要复制资源！'
      end
    end
    redirect_to :action=>'list'
  end

  def add_tag_selected    
    tag_name = params[:tag_name]
    if not params[:resource_id].nil?
      unless tag_name.nil?
        begin
          Resource.transaction do
            params[:resource_id].each do |res_id|
              unless res_id.empty?
                resource = Resource.find(res_id)
                is_do = true
                r_tag = resource.res_tag
                r_tag.each {
                  |res_tag|
                  if tag_name == res_tag.tag.name
                    is_do = false
                  end
                }
                if is_do
                  le = $res_default
                  tag = Tag.find_last_by_name tag_name
                  #判断是否存在tag
                  if tag.nil?
                    tag = Tag.new
                    tag.name = tag_name
                    tag.level = le
                    tag.save
                  else
                    #判断级别
                    r_tag.each do | res_tag |
                      res_tag.tag.level > tag.level
                      le = tag.level
                    end
                  end
                  #保存更新资源
                  rs = ResTag.create(:resource => resource,:tag => tag)
                  resource.res_tag <<  rs
                  tag.res_tag <<  rs
                  rs.save
                end
              end
            end
          end
          flash[:notice] = "移动资源成功！"
        rescue
          flash[:notice] = "移动资源失败！"
        end
      else
        flash[:notice] = '请选择要移动的资源！'
      end
    end
    redirect_to :action=>'list'
  end

  #推荐到精选栏目
  def to_channel
    if not params[:resource_id].nil?
      channel_chose = Channel.find_last_by_channel_type "3"
      unless channel_chose.nil?
        begin
          Resource.transaction do
            params[:resource_id].each do |res_id|
              unless res_id.empty?
                @resource = Resource.find(res_id)
                @resource.update_attributes({:channel_id => channel_chose.id});
              end
            end
          end
          flash[:notice] = "推荐成功！"
        rescue
          flash[:notice] = "推荐失败！"
        end
      end
    else
      flash[:notice] = '请选择要推荐的资源！'
    end
    redirect_to :action=>'list'
  end

  #从精选频道移除
  def move_channel
    if not params[:resource_id].nil?          
      begin
        Resource.transaction do
          params[:resource_id].each do |res_id|
            unless res_id.empty?
              @resource = Resource.find(res_id)
              @resource.update_attributes({:channel_id => nil});
            end
          end
        end
        flash[:notice] = "推荐成功！"
      rescue
        flash[:notice] = "推荐失败！"
      end
    else
      flash[:notice] = '请选择要推荐的资源！'
    end
    redirect_to :action=>'list'
  end
end

